import os
import sys
import json
import random

if len(sys.argv) < 2:
    print("usage: python3 run_test.py less_case.json  10\n"
          "or \n"
          "python3 run_test.py less_case.json  10 cpu_result.csv")

case_file_name = sys.argv[1]
run_time = 1
if len(sys.argv) > 2:
    run_time = int(sys.argv[2])
if len(sys.argv) < 4:
    result_file_name = "result_file.csv"
else:
    result_file_name = sys.argv[3]
device_id = random.randint(0,7)
run_test_cmd = "python3 msopst run -i {} -soc Ascend910A -out aicpu_st/out/  -d {} -conf msopst.ini 2>&1 |tee run.log".format(
    sys.argv[1], device_id)
os.system("rm {}".format(result_file_name))


def get_case_list(run_log):
    case_name_list = []
    for case_name_info in run_log:
        case_name = case_name_info.strip().split("\'")[1]
        case_name_list.append(case_name)
    return case_name_list


for i in range(0, run_time):
    result_file = open("tmp.csv", "w")
    try:
        result_list = open(result_file_name, "r").readlines()
    except:
        result_list = []
    os.system("rm -rf aicpu_st/")
    os.system("rm -rf  ~/ascend/log/*")
    os.system(run_test_cmd)
    result = os.popen("grep -rn  \"run time is\" ~/ascend/log/ ").readlines()
    run_log = os.popen("grep -rn  \"\' run success\" run.log").readlines()
    case_name_list = []
    with open(sys.argv[1], 'r') as load_f:
        load_dict = json.load(load_f)
        case_name_list = get_case_list(run_log)
    for i in result:
        index = result.index(i)
        time_tmp = i.split("run time is")[1]
        time_used = time_tmp[time_tmp.index("[") + 1:time_tmp.index("]")]
        case_name = case_name_list[index]
        try:
            if len(result_list) == 0:
                str_result = case_name + "," + time_used + "\n"
                result_file.write(str_result)
            else:
                str_result = result_list[index].replace("\n", "")
                str_result = str_result + "," + time_used + "\n"
                result_file.write(str_result)
        except Exception as e:
            s = sys.exc_info()
            print('error when run run_test.py,', s[1], s[2].tb_lineno)

    result_file.close()
    os.system("mv tmp.csv {}".format(result_file_name))
